package com.heima.aliyun.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component
@EnableConfigurationProperties(AliyunProperties.class)
public class GreenTextScan {

    @Resource
    private AliyunProperties aliyunProperties;

    public Map<String, String> greenTextScan(String content) throws Exception {
        IClientProfile profile = DefaultProfile
                .getProfile("cn-shanghai", aliyunProperties.getAccessKeyId(), aliyunProperties.getSecret());
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON);
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST);
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId("cn-shanghai");
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符
         */
        task1.put("content", content);
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景，文本垃圾检测传递：antispam
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        System.out.println(JSON.toJSONString(data, true));
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);

        Map<String, String> resultMap = new HashMap<>();

        HttpResponse httpResponse = client.doAction(textScanRequest);
        if (!httpResponse.isSuccess()) {
            log.error("阿里云文本审核失败 , 失败原因:{}", new String(httpResponse.getHttpContent(), "UTF-8"));
            return null;
        }

        JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
        if (200 != scrResponse.getInteger("code")) {
            log.error("阿里云文本审核失败 ,失败状态码:{}, 失败原因:{}", scrResponse.getInteger("code"), new String(httpResponse.getHttpContent(), "UTF-8"));
            return null;
        }

        JSONArray taskResults = scrResponse.getJSONArray("data");
        for (Object taskResult : taskResults) {
            if (200 == ((JSONObject) taskResult).getInteger("code")) {
                JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                for (Object sceneResult : sceneResults) {
                    String scene = ((JSONObject) sceneResult).getString("scene");
                    String label = ((JSONObject) sceneResult).getString("label");
                    String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                    System.out.println("suggestion = [" + label + "]");
                    if (!suggestion.equals("pass")) {
                        resultMap.put("suggestion", suggestion);
                        resultMap.put("label", label);
                        return resultMap;
                    }

                }
            } else {
                return null;
            }
        }

        resultMap.put("suggestion", "pass");
        return resultMap;
    }

}